﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using Microsoft.Phone.Tasks;
using unifiqAnthony.GeocodeService;
using System.Windows.Media;
using DeepForest.Phone.Assets.Tools;
using System.IO;
using System.Windows.Media.Imaging;
using System.Net;

namespace unifiqAnthony
{
    public partial class ListingUpdateConfirm : PhoneApplicationPage
    {
        
        internal const string id = "Aggp0yd8miqzaqQrXChtjs8v2m4nlHd3lFn06-W9gu7ZI4KBhTzUddWbVjayXfTV"; //Bing key


        unifiqAnthony.GeocodeService.Location listLoc = new unifiqAnthony.GeocodeService.Location();


        UnifiqSvc.Listing listing = null;
        List<byte[]> byteList = null;

        public ListingUpdateConfirm()
        {
            InitializeComponent();
        }

        void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                MessageBox.Show(e.ChosenPhoto.Length.ToString());
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Show Loading Screen
            tb_loading.Text = "Finding Location on Map";
            progressOverlay.Show();

            // Populate Fields
            loadData();

            String address = listing.blkNo + " " + listing.stName + " " + listing.stNo;

            LoadLocations(address);
        }

        void loadData()
        {
            var obj = App.Current as App;

            
            // Load Photos
            byteList = obj.byteList;

            int insCount = 1;
            foreach (byte[] x in byteList)
            {
                System.Diagnostics.Debug.WriteLine(x==null);
                
                if (x != null)
                {
                    Image img;
                    if (insCount == 1)
                    {
                        img = image1;
                        insCount++;
                    }
                    else if (insCount == 2)
                    {
                        img = image2;
                        insCount++;
                    }
                    else
                    {
                        img = image3;
                    }

                    BitmapImage bmp = new BitmapImage();
                    bmp.SetSource(new MemoryStream(x));

                    //bmp.SetSource(ms);
                    img.Source = bmp;
                }
                
                 
            }
            

            // Get Listing Details
            UnifiqSvc.Listing l = obj.listing;
            this.listing = l;

            string msg = "";
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
                textBlock1.Text = msg;
            int uid;

            uid = l.uid;
            tb_stName.Text = l.stName;
            tb_stNo.Text = l.stNo;
            tb_blkNo.Text = l.blkNo;
            tb_doorNo.Text = l.doorNo;
            tb_apptNo.Text = l.apptNo;
            tb_zipCode.Text = l.zipCode;
            tb_bldngName.Text = l.bldngName;
            tb_contactNo.Text = l.contactNo;
            tb_desc.Text = l.description;
            tb_fullName.Text = l.contactName;
            tb_noOfTenants.Text = l.noOfTenants.ToString();
            tb_fee.Text = l.fee.ToString();
        }

        private void LoadAddressPushpin(double lat, double lon)
        {
            System.Diagnostics.Debug.WriteLine("Execute: " + lat + ", " + lon);
            Pushpin pin = new Pushpin();
            GeoCoordinate geo = new GeoCoordinate(lat, lon);

            Map.ZoomLevel = 17;
            Map.Center = geo;

            pin.Location = geo;
            pin.Template = this.Resources["listingPin"] as ControlTemplate;
            Map.Children.Add(pin);
        }

        private void LoadLocations(string address)
        {
            GeocodeServiceClient geocodeService = new GeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            GeocodeRequest geocodeRequest = new GeocodeRequest();
            {  
                
                geocodeRequest.Credentials = new unifiqAnthony.GeocodeService.Credentials() { ApplicationId = id };
                geocodeRequest.Query = "singapore "+ address;//"14820 NE 36th st redmond, wa 98052";//address;
                System.Diagnostics.Debug.WriteLine(geocodeRequest.Query);
                geocodeRequest.Options = new GeocodeOptions() { Filters = new System.Collections.ObjectModel.ObservableCollection<FilterBase>() };
            };
            geocodeRequest.Options.Filters.Add(new ConfidenceFilter() { MinimumConfidence = Confidence.Low });
            geocodeService.GeocodeAsync(geocodeRequest);

            // 
            geocodeService.GeocodeCompleted += (sender, e) => geoCode_GeocodeCompleted(sender, e);
        }

        /**
         * Methods called when the research is completed by the service 
         * 
         * */
        void geoCode_GeocodeCompleted(object sender, GeocodeService.GeocodeCompletedEventArgs e)
        {
            System.Text.StringBuilder result = new System.Text.StringBuilder();

            if (e.Result.Results.Count > 0)
            {
                GeocodeResult svcResult = e.Result.Results[0];

                // The service returns a list of locations. We will display each of them
                //foreach (unifiqAnthony.GeocodeService.Location loc in svcResult.Locations.ToList())
                ///{
                    unifiqAnthony.GeocodeService.Location loc = svcResult.Locations.ToList().First();
                    result.Append(loc.Latitude).Append(' ');
                    result.Append(loc.Longitude).Append('\n');
                    System.Diagnostics.Debug.WriteLine(loc.Latitude);
                    System.Diagnostics.Debug.WriteLine(loc.Longitude);
                    System.Diagnostics.Debug.WriteLine(svcResult.Locations.ToList().Count);
                    LoadAddressPushpin(loc.Latitude,loc.Longitude);
                    listing.lat = loc.Latitude;
                    listing.lon = loc.Longitude;
                    
                    //Hide Loading Screen
                    progressOverlay.Hide();
                //}
            }
            else
            {
                result.Append("No location found");
                NotificationTool.Show(
                "No Location Found",
                "Address may be invalid, or there is a server error. Please try again.",
                new NotificationAction("Ok", () => { NavigationService.GoBack();}));
            }
            //tb_desc.Text = result.ToString();
        }

        private readonly CredentialsProvider _credentialsProvider = new ApplicationIdCredentialsProvider(id);

        public CredentialsProvider CredentialsProvider
        {
            get { return _credentialsProvider; }
        }

        void dbSvc_insertListingCompleted(object sender, UnifiqSvc.insertListingCompletedEventArgs e)
        {
            // Hide Loading Screen
            progressOverlay.Hide();

            bool suc = e.Result;

            System.Diagnostics.Debug.WriteLine(listing.ToString());

            if (suc)
            {
                NotificationTool.Show(
                "Success",
                "Your listing is successfully posted!",
                new NotificationAction("OK", () => { NavigationService.Navigate(new Uri("/ListingMain.xaml", UriKind.Relative)); }));
            }
            else    
            {
                NotificationTool.Show(
                "Posting failed",
                "An error has occured; " + e.Error + "\n Please contact the Unifiq Team about this error",
                new NotificationAction("Ok", () => { }));
            }

        }

        void previewImage(int pos)
        {
            NavigationService.Navigate(new Uri("/ImagePreview.xaml?pos=" + pos, UriKind.Relative));
        }

        private void btn_image1_Click(object sender, RoutedEventArgs e)
        {
            if (image1.Source != null)
            {
                previewImage(1);
            }
            
        }

        private void btn_image2_Click(object sender, RoutedEventArgs e)
        {
            if (image2.Source != null)
            {
                previewImage(2);
            }
        }

        private void btn_image3_Click(object sender, RoutedEventArgs e)
        {
            //System.Diagnostics.Debug.WriteLine(image1.Source==null);
            
            if (image3.Source != null)
            {
                previewImage(3);
            }
        }

        private void btn_update_Click(object sender, RoutedEventArgs e)
        {
            // Show Loading Screen
            tb_loading.Text = "Posting in Progress";
            progressOverlay.Show();

            // Store bytes to Listing obj
            int count = 1;
            foreach (byte[] x in byteList)
            {
                if (x != null)
                {
                    if (count == 1)
                    {
                        listing.img1 = x;
                    }
                    else if (count == 2)
                    {
                        listing.img2 = x;
                    }
                    else if (count == 3)
                    {
                        listing.img3 = x;
                    }
                    count++;
                }

            }

            UnifiqSvc.ServiceSoapClient dbSvc = new UnifiqSvc.ServiceSoapClient();
            dbSvc.UpdateListingCompleted += new EventHandler<UnifiqSvc.UpdateListingCompletedEventArgs>(dbSvc_UpdateListingCompleted);
            dbSvc.UpdateListingAsync(listing);
        }

        void dbSvc_UpdateListingCompleted(object sender, UnifiqSvc.UpdateListingCompletedEventArgs e)
        {
            bool suc = e.Result;

            System.Diagnostics.Debug.WriteLine(listing.ToString());

            if (suc)
            {
                NotificationTool.Show(
                "Update Success",
                "Your listing is successfully updated!",
                new NotificationAction("OK", () =>
                {
                    // Remove Back Entry
                    NavigationService.RemoveBackEntry();

                    // Set updated Listing to obj
                    var obj = App.Current as App;
                    obj.listing = listing;

                    // Navigate to ListingView
                    NavigationService.RemoveBackEntry();
                    NavigationService.RemoveBackEntry();
 
                    NavigationService.Navigate(new Uri("/ListingList.xaml?back=" + "true", UriKind.Relative));

                }));
            }
            else
            {
                NotificationTool.Show(
                "Update Failed",
                "An error has occured; " + e.Error + "\n Please contact the Unifiq Team about this error",
                new NotificationAction("Ok", () => { }));
            }

            progressOverlay.Hide();

        }

    }
}